<template>
  <view class="profile-page">
    <image src="/static/images/bg-user.png" class="bg-image" mode="aspectFill"></image>
    <!-- 头部区域 -->
    <view class="header-section">
      <!-- 状态栏占位 -->
      <view class="status-bar"></view>
      
      <!-- 标题栏 -->
      <view class="title-bar">
        <text class="page-title">我的</text>
      </view>
      
      <!-- 用户信息区域 -->
      <view class="user-info-section">
        <view class="user-avatar-wrapper">
          <image 
            :src="userAvatar || '/static/images/default-avatar.png'" 
            class="user-avatar" 
            mode="aspectFill"
            @click="changeAvatar"
          ></image>
        </view>
        
        <view class="user-details">
          <text v-if="isLogin" class="user-nickname">{{ userNickname }}</text>
          <text v-else class="user-login-text" @click="showLogin = true">登录</text>
        </view>
        
        <view class="edit-profile-btn" @click="editProfile">
          <image src="/static/images/setting.png" class="setting-icon" mode="aspectFit"></image>
        </view>
      </view>
    </view>
    
    <!-- 功能菜单区域 -->
    <view class="menu-section">
      <!-- VIP开通 -->
      <view class="menu-item" @click="goToVip">
        <view class="menu-icon">
          <image src="/static/images/menu-vip.png" mode="aspectFit" class="menu-image"></image>
        </view>
        <text class="menu-text">开通VIP</text>
        <u-icon name="arrow-right" size="16" color="#c8c9cc"></u-icon>
      </view>
      
      <!-- 我的关注 -->
      <view class="menu-item" @click="goToFavorites">
        <view class="menu-icon">
          <image src="/static/images/menu-favorites.png" mode="aspectFit" class="menu-image"></image>
        </view>
        <text class="menu-text">我的关注</text>
        <u-icon name="arrow-right" size="16" color="#c8c9cc"></u-icon>
      </view>
      
      <!-- 邀请新用户 -->
      <view class="menu-item" @click="goToInvite">
        <view class="menu-icon">
          <image src="/static/images/menu-invite.png" mode="aspectFit" class="menu-image"></image>
        </view>
        <text class="menu-text">邀请新用户</text>
        <u-icon name="arrow-right" size="16" color="#c8c9cc"></u-icon>
      </view>

      <!-- 输入邀请码（仅当未绑定邀请人时显示） -->
      <view class="menu-item" v-if="isLogin && (!userInfo.inviter_id || userInfo.inviter_id === 0)" @click="openInviteCodeModal">
        <view class="menu-icon">
          <image src="/static/images/menu-invite.png" mode="aspectFit" class="menu-image"></image>
        </view>
        <text class="menu-text">输入邀请码</text>
        <u-icon name="arrow-right" size="16" color="#c8c9cc"></u-icon>
      </view>
      
      <!-- VIP交流群 -->
      <view class="menu-item" @click="goToGroup">
        <view class="menu-icon">
          <image src="/static/images/menu-group.png" mode="aspectFit" class="menu-image"></image>
        </view>
        <text class="menu-text">会员交流群</text>
        <u-icon name="arrow-right" size="16" color="#c8c9cc"></u-icon>
      </view>
      
      <!-- 用户服务协议 -->
      <view class="menu-item" @click="goToAgreement('service')">
        <view class="menu-icon">
          <image src="/static/images/menu-agreement.png" mode="aspectFit" class="menu-image"></image>
        </view>
        <text class="menu-text">用户服务协议</text>
        <u-icon name="arrow-right" size="16" color="#c8c9cc"></u-icon>
      </view>
      
      <!-- 隐私政策 -->
      <view class="menu-item" @click="goToAgreement('privacy')">
        <view class="menu-icon">
          <image src="/static/images/menu-privacy.png" mode="aspectFit" class="menu-image"></image>
        </view>
        <text class="menu-text">隐私政策</text>
        <u-icon name="arrow-right" size="16" color="#c8c9cc"></u-icon>
      </view>
    </view>
    
    <!-- 登录弹窗 -->
    <login-modal 
      :visible="showLogin" 
      @close="showLogin = false"
      @success="handleLoginSuccess"
    ></login-modal>
    
    <!-- VIP交流群弹窗 -->
    <u-popup 
      :show="showGroupModal" 
      mode="center" 
      :round="20"
      @close="showGroupModal = false"
      @click-overlay="showGroupModal = false"
    >
      <view class="group-modal">
          <image src="/static/images/wechat-group-bg.png" class="group-header-bg-image" mode="widthFix"></image>
          <view class="qr-code-section">
            <view class="qr-code-wrapper">
              <image 
                :src="serverGroupQrUrl" 
                class="qr-code-image"
                mode="aspectFit"
                @longpress="handleQRLongPress"
              ></image>
            </view>
          </view>
        </view>
    </u-popup>

    <!-- 输入邀请码弹窗 -->
    <u-popup 
      :show="showInviteCodeModal" 
      mode="center" 
      :round="20"
      @close="showInviteCodeModal = false"
      @click-overlay="showInviteCodeModal = false"
    >
      <view style="width: 600rpx; padding: 30rpx; background: #fff; border-radius: 20rpx;">
        <view style="font-size: 32rpx; font-weight: bold; margin-bottom: 20rpx;">输入邀请码</view>
        <u-input v-model="inviteCodeInput" placeholder="请输入邀请码" :border="true" />
        <view style="margin-top: 16rpx; padding: 16rpx; background: #fff4f4; border: 1rpx solid #ffd7d7; border-radius: 12rpx;">
          <text style="font-size: 26rpx; color: #c23b3b;">
            重要提醒：邀请码绑定仅有一次机会，绑定后不可更改；且绑定会为邀请人产生收益，请谨慎确认。
          </text>
        </view>
        <view style="margin-top: 24rpx; display: flex; gap: 20rpx;">
          <u-button type="default" @click="showInviteCodeModal = false">取消</u-button>
          <u-button type="primary" :loading="inviteCodeSubmitting" @click="submitInviteCode">确定</u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
/**
 * 个人中心页面
 * @author 王勇程 <laughskydragon@qq.com>
 */
import { userApi, uploadApi } from '@/api'
import { uploadImage } from '@/api/upload'
import { normalizeImageUrl } from '@/utils/common'
import { getBalance } from '@/api/invite'
import { showToast, showLoading, hideLoading } from '@/utils/common.js'
import LoginModal from '@/components/login-modal/login-modal.vue'
import { processInviteRelation } from '@/api/invite'
import APP_CONFIG from '@/config'

const { getUserInfo, updateUserInfo } = userApi

export default {
  components: {
    LoginModal
  },
  
  data() {
    return {
      showLogin: false,
      showGroupModal: false,
      showInviteCodeModal: false,
      inviteCodeInput: '',
      inviteCodeSubmitting: false,
      userBalance: {
        withdrawable: 0,
        total_earnings: 0,
        pending: 0
      },
      serverGroupQrUrl: APP_CONFIG.BASE_URL + '/static/images/wechat-group-qr.png'
    }
  },
  
  computed: {
    userInfo() {
      return this.$store.getters['user/userInfo']
    },
    
    isLogin() {
      return this.$store.getters['user/isLogin']
    },
    userNickname() {
      return this.$store.getters['user/userNickname']
    },
    userAvatar() {
      return normalizeImageUrl(this.$store.getters['user/userInfo']?.avatar)
    }
  },
  
  onLoad() {
    // this.checkLoginStatus() // 移除自动检查登录状态
  },
  
  onShow() {
    // this.checkLoginStatus() // 移除自动检查登录状态
    // 每次进入页面时，如果已登录，则刷新用户信息和余额
    if (this.isLogin) {
      this.refreshUserInfo()
      this.loadUserBalance()
    }
  },
  
  methods: {
    // 检查登录状态
    checkLoginStatus() {
      // 此方法不再用于自动弹出登录框，仅用于判断是否登录
      return this.isLogin
    },

    // 加载用户余额
    async loadUserBalance() {
      try {
        const res = await getBalance()
        const payload = (res && typeof res === 'object' && res.code !== undefined) ? res.data : res
        if (payload) {
          this.userBalance = {
            withdrawable: payload.withdrawable || 0,
            total_earnings: payload.total_earnings || 0,
            pending: payload.pending || 0
          }
        }
      } catch (error) {
        console.error('加载用户余额失败:', error)
      }
    },

    // 格式化金额
    formatAmount(amount) {
      return parseFloat(amount || 0).toFixed(2)
    },
    
    // 刷新用户信息
    async refreshUserInfo() {
      if (!this.isLogin) return
      
      try {
        const info = await getUserInfo()
        await this.$store.dispatch('user/updateUserInfo', info)
      } catch (error) {
        console.error('刷新用户信息失败:', error)
      }
    },

    // 处理登录成功
    handleLoginSuccess() {
      this.showLogin = false
      this.refreshUserInfo()
      this.loadUserBalance()
      // 登录成功后检查是否需要完善资料
      this.checkProfileCompleteness()
    },

    // 检查资料完整性
    checkProfileCompleteness() {
      if (!this.isLogin) return
      
      // 延迟执行，确保用户信息已更新
      setTimeout(() => {
        const userInfo = this.userInfo
        const missingFields = []
        
        // 检查头像
        if (!userInfo.avatar || userInfo.avatar === '/static/images/default-avatar.png') {
          missingFields.push('头像')
        }
        
        // 检查昵称
        if (!userInfo.nickname || userInfo.nickname.trim() === '') {
          missingFields.push('昵称')
        }
        
        // 如果有缺失的字段，提醒用户完善资料
        if (missingFields.length > 0) {
          uni.showModal({
            title: '完善资料',
            content: `您的${missingFields.join('、')}信息不完整，是否立即完善？`,
            confirmText: '去完善',
            cancelText: '稍后再说',
            success: (res) => {
              if (res.confirm) {
                this.editProfile()
              }
            }
          })
        }
      }, 1000)
    },

    // 更换头像
    changeAvatar() {
      return;
      if (!this.isLogin) {
        this.showLogin = true
        return
      }
      
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          const tempFilePath = res.tempFilePaths[0]
          await this.uploadUserAvatar(tempFilePath)
        }
      })
    },

    // 上传头像
    async uploadUserAvatar(filePath) {
      showLoading('上传中...')
      
      try {
        const uploadRes = await uploadImage(filePath)
        const info = uploadRes?.upload_info || uploadRes
        await updateUserInfo({ avatar_id: info.id })
        const userInfo = await getUserInfo()
        await this.$store.dispatch('user/updateUserInfo', userInfo)
        showToast('头像更新成功', 'success')
      } catch (error) {
        console.error('上传头像失败:', error)
        showToast('上传失败', 'none')
      } finally {
        hideLoading()
      }
    },

    // 编辑个人资料
    editProfile() {
      if (!this.isLogin) {
        this.showLogin = true
        return
      }
      
      uni.navigateTo({
        url: '/pages/user/edit-profile'
      })
    },

    // 跳转到VIP页面
    goToVip() {
      if (!this.isLogin) {
        this.showLogin = true
        return
      }
      
      uni.navigateTo({
        url: '/pages/user/vip/index'
      })
    },

    // 跳转到我的关注
    goToFavorites() {
      if (!this.isLogin) {
        this.showLogin = true
        return
      }
      
      uni.navigateTo({
        url: '/pages/user/favorites'
      })
    },

    // 跳转到浏览历史
    goToHistory() {
      if (!this.isLogin) {
        this.showLogin = true
        return
      }
      
      uni.navigateTo({
        url: '/pages/user/history'
      })
    },

    // 跳转到邀请页面
    goToInvite() {
      if (!this.isLogin) {
        this.showLogin = true
        return
      }
      
      uni.navigateTo({
        url: '/pages/user/invite/index'
      })
    },

    // 打开输入邀请码弹窗
    openInviteCodeModal() {
      if (!this.isLogin) {
        this.showLogin = true
        return
      }
      this.inviteCodeInput = ''
      this.showInviteCodeModal = true
    },

    // 提交邀请码
    async submitInviteCode() {
      if (!this.inviteCodeInput) {
        uni.showToast({ title: '请输入邀请码', icon: 'none' })
        return
      }
      uni.showModal({
        title: '重要提醒',
        content: '邀请码绑定仅有一次机会，绑定后不可更改，并会为邀请人产生收益。确认绑定吗？',
        confirmText: '确认绑定',
        cancelText: '取消',
        success: async (modalRes) => {
          if (!modalRes.confirm) return
          this.inviteCodeSubmitting = true
          try {
            const res = await processInviteRelation({ invite_code: this.inviteCodeInput })
            if (res && res.code === 0) {
              uni.showToast({ title: '绑定成功', icon: 'success' })
              this.showInviteCodeModal = false
              await this.refreshUserInfo()
            } else {
              uni.showToast({ title: (res && res.msg) || '绑定失败', icon: 'none' })
            }
          } catch (e) {
            const msg = (e && (e.msg || e.message)) ? (e.msg || e.message) : '网络错误，请重试'
            uni.showToast({ title: msg, icon: 'none' })
          } finally {
            this.inviteCodeSubmitting = false
          }
        }
      })
    },

    // 跳转到提现页面
    goToWithdraw() {
      if (!this.isLogin) {
        this.showLogin = true
        return
      }
      
      uni.navigateTo({
        url: '/pages/user/withdraw/index'
      })
    },
    
    // 跳转到交流群
    goToGroup() {
      if (!this.isLogin) {
        this.showLogin = true
        return
      }
      
      this.showGroupModal = true
    },
    
    // 跳转到协议页面
    goToAgreement(type) {
      let articleId = 2 // 默认用户服务协议
      let title = '用户服务协议'
      
      if (type === 'privacy') {
        articleId = 3
        title = '隐私政策'
      } else if (type === 'faq') {
        articleId = 4
        title = '常见问题'
      }
      
      uni.navigateTo({
        url: `/pages/article/detail?id=${articleId}&title=${encodeURIComponent(title)}`
      })
    },
    
    // 处理二维码长按
    handleQRLongPress() {
      uni.showToast({
        title: '请在微信中识别二维码',
        icon: 'none',
        duration: 2000
      })
      
      // 尝试调用微信小程序的识别二维码功能
       // #ifdef MP-WEIXIN
       try {
         wx.previewImage({
           urls: [this.serverGroupQrUrl],
           current: this.serverGroupQrUrl
         })
       } catch (error) {
         console.log('预览二维码失败:', error)
       }
       // #endif
    }
  }
}
</script>

<style scoped>
.profile-page {
      min-height: 100vh;
      background-color: #f4f3f8;
      position: relative; /* 确保背景图片定位正确 */
}

.bg-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 360rpx;
  z-index: 0;
}

/* 顶部渐变背景区域 */
.header-section {
  position: relative;
  padding-bottom: 40rpx;
  padding-top: var(--status-bar-height);
  z-index: 1;
}

.status-bar {
  height: var(--status-bar-height, 44rpx);
}

.title-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0rpx 30rpx;
  height: 60rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #fff;
  text-align: center;
  width: 100%;
}

.header-actions {
  display: flex;
  align-items: center;
}

.action-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 20rpx;
  backdrop-filter: blur(10rpx);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
}

/* 用户信息区域 */
.user-info-section {
  display: flex;
  align-items: center;
  padding: 0 30rpx 30rpx;
  position: relative;
}

.user-avatar-wrapper {
  position: relative;
  margin-right: 30rpx;
}

.user-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  border: 4rpx solid #FFF;
  background-color: #FFF;
}

.user-details {
  flex: 1;
}

.user-nickname {
  font-size: 32rpx;
  font-weight: bold;
  color: #000;
  display: block;
}

.edit-profile-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10rpx);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
}
.setting-icon { width: 32rpx; height: 32rpx; }

/* 余额卡片 */
.balance-card {
  margin: 20rpx 30rpx;
  padding: 35rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 24rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 12rpx 40rpx rgba(102, 126, 234, 0.25);
}

.balance-info {
  flex: 1;
}

.balance-label {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  display: block;
  margin-bottom: 10rpx;
}

.balance-amount {
  display: flex;
  align-items: baseline;
}

.currency {
  font-size: 28rpx;
  color: #fff;
  margin-right: 5rpx;
}

.amount {
  font-size: 48rpx;
  font-weight: bold;
  color: #fff;
}

.balance-actions {
  display: flex;
  gap: 20rpx;
}

.balance-btn {
  padding: 16rpx 32rpx;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 50rpx;
  border: 2rpx solid rgba(255, 255, 255, 0.3);
}

.balance-btn text {
  font-size: 24rpx;
  color: #fff;
  font-weight: 500;
}

.balance-btn.secondary {
  background-color: transparent;
  border-color: rgba(255, 255, 255, 0.5);
}

/* 功能菜单区域 */
.menu-section {
  background-color: #fff;
  margin: 20rpx 30rpx;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
  position: relative;
  z-index: 1;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 40rpx 35rpx;
  border-bottom: 1rpx solid #f8f8f8;
  position: relative;
  transition: background-color 0.2s ease;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-item.vip-item {
  background: linear-gradient(90deg, #fff8f5 0%, #fff 100%);
  border-left: 4rpx solid #ff6b35;
}

.menu-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: #fff2f0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 107, 53, 0.15);
}

.vip-icon {
  background: linear-gradient(135deg, #ffd700 0%, #ffb347 100%);
}

.menu-image {
  width: 32rpx;
  height: 32rpx;
}

.menu-text {
  flex: 1;
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.menu-status {
  font-size: 24rpx;
  color: #999;
  margin-right: 20rpx;
}

/* VIP交流群弹窗样式 */
.group-modal {
  width: 600rpx;
  background-color: transparent; /* 背景图已包含背景色 */
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.15);
  padding: 0;
  position: relative;
}

.group-header-bg-image {
  width: 100%;
  height: auto;
  display: block;
}

.qr-code-section {
  position: absolute;
  width: 100%;
  text-align: center;
  top: 260rpx;
  left: 0;
}

.qr-code-wrapper {
  position: relative;
  display: inline-block;
  margin-bottom: 30rpx;
}

.qr-code-image {
  width: 300rpx;
  height: 300rpx;
  border-radius: 24rpx;
  border: 1rpx solid #e8e8e8;
  background-color: #fff;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
}

.finger-icon {
  position: absolute;
  bottom: 20rpx;
  right: 20rpx;
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  background-color: rgba(255, 107, 53, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  animation: fingerPulse 2s infinite;
}

@keyframes fingerPulse {
  0%, 100% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.8;
  }
}

.qr-hint {
  font-size: 28rpx;
  color: #666;
  display: block;
}
.user-login-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #fff;
  text-decoration: underline;
  cursor: pointer;
}
</style>
